package com.wg.neptune.cluster.strategy;

import com.wg.neptune.cluster.Cluster;
import com.wg.neptune.model.ProviderService;

import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by mc on 18/6/6.
 */
public class RoundClusterStrategy implements Cluster {


    private  int index = 0;

    private Lock lock = new ReentrantLock();
    /**
     * 轮询负载均衡算法
     * @param providerServices
     * @return
     */
    public ProviderService select(List<ProviderService> providerServices) {

        ProviderService providerService = null;
        try {
            lock.lock();
            if(index >= providerServices.size()){
                index = 0;
            }
            providerService = providerServices.get(index);
        }catch (Exception e){

        }finally {
            lock.unlock();
        }
        if(providerService == null){
            providerService = providerServices.get(0);
        }
        return providerService;
    }
}
